package com.sqlcheck.service.impl;

import com.sqlcheck.common.exception.BusinessException;
import com.sqlcheck.entity.ScanResult;
import com.sqlcheck.entity.ScanTask;
import com.sqlcheck.service.ReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 报告服务实现类
 * 处理各种格式的报告生成
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ReportServiceImpl implements ReportService {

    @Override
    public byte[] generateExcelReport(ScanTask task, List<ScanResult> scanResults) {
        try (XSSFWorkbook workbook = new XSSFWorkbook();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            log.info("开始生成Excel报告，任务ID: {}", task.getId());

            // 创建样式
            Map<String, CellStyle> styles = createCellStyles(workbook);

            // Sheet 1: 任务概览
            createTaskOverviewSheet(workbook, task, scanResults, styles);

            // Sheet 2: 问题详情
            createProblemDetailsSheet(workbook, scanResults, styles);

            // Sheet 3: AI分析专用（如果有AI分析结果）
            List<ScanResult> aiResults = scanResults.stream()
                    .filter(result -> "AI".equals(result.getAnalysisEngine()) ||
                            Boolean.TRUE.equals(result.getAiOptimized()) ||
                            result.getAiConfidenceScore() != null)
                    .collect(Collectors.toList());
            if (!aiResults.isEmpty()) {
                createAiAnalysisSheet(workbook, task, aiResults, styles);
            }

            workbook.write(outputStream);
            log.info("Excel报告生成完成，任务ID: {}, 文件大小: {} bytes", task.getId(), outputStream.size());
            return outputStream.toByteArray();

        } catch (Exception e) {
            log.error("生成Excel报告失败，任务ID: {}", task.getId(), e);
            throw new BusinessException("生成Excel报告失败: " + e.getMessage());
        }
    }

    @Override
    public byte[] generatePdfReport(ScanTask task, List<ScanResult> scanResults) {
        throw new BusinessException("PDF报告生成功能暂未实现");
    }

    @Override
    public String generateHtmlReport(ScanTask task, List<ScanResult> scanResults) {
        throw new BusinessException("HTML报告生成功能暂未实现");
    }

    @Override
    public String generateReportFileName(ScanTask task, String format) {
        // 使用英文文件名，避免URL编码问题
        String taskName = task.getTaskName() != null ? sanitizeFileName(task.getTaskName()) : "Task_" + task.getId();
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String extension;

        switch (format.toLowerCase()) {
            case "excel":
                extension = ".xlsx";
                break;
            case "pdf":
                extension = ".pdf";
                break;
            case "html":
                extension = ".html";
                break;
            default:
                extension = ".xlsx";
        }

        return String.format("SQLCheck_Report_%s_%s%s", taskName, date, extension);
    }

    /**
     * 清理文件名，移除特殊字符和中文字符
     */
    private String sanitizeFileName(String fileName) {
        if (fileName == null)
            return "Unknown";

        // 移除或替换特殊字符，保留字母、数字、下划线、连字符
        String sanitized = fileName.replaceAll("[^a-zA-Z0-9_\\-\\u4e00-\\u9fff]", "_");

        // 如果包含中文，转换为拼音或使用简化名称
        if (sanitized.matches(".*[\\u4e00-\\u9fff].*")) {
            // 简化中文文件名
            if (sanitized.contains("数据库")) {
                sanitized = "Database_Scan";
            } else if (sanitized.contains("Git")) {
                sanitized = "Git_Scan";
            } else if (sanitized.contains("项目")) {
                sanitized = "Project_Scan";
            } else {
                sanitized = "Custom_Task";
            }
        }

        // 限制长度
        if (sanitized.length() > 50) {
            sanitized = sanitized.substring(0, 50);
        }

        return sanitized;
    }

    /**
     * 创建Excel单元格样式
     */
    private Map<String, CellStyle> createCellStyles(XSSFWorkbook workbook) {
        Map<String, CellStyle> styles = new HashMap<>();

        // 标题样式
        CellStyle titleStyle = workbook.createCellStyle();
        Font titleFont = workbook.createFont();
        titleFont.setBold(true);
        titleFont.setFontHeightInPoints((short) 14);
        titleStyle.setFont(titleFont);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        styles.put("title", titleStyle);

        // 表头样式
        CellStyle headerStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerFont.setFontHeightInPoints((short) 12);
        headerStyle.setFont(headerFont);
        headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setBorderTop(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);
        headerStyle.setBorderLeft(BorderStyle.THIN);
        styles.put("header", headerStyle);

        // 普通数据样式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setBorderBottom(BorderStyle.THIN);
        dataStyle.setBorderTop(BorderStyle.THIN);
        dataStyle.setBorderRight(BorderStyle.THIN);
        dataStyle.setBorderLeft(BorderStyle.THIN);
        dataStyle.setWrapText(true);
        styles.put("data", dataStyle);

        // 标签样式
        CellStyle labelStyle = workbook.createCellStyle();
        Font labelFont = workbook.createFont();
        labelFont.setBold(true);
        labelStyle.setFont(labelFont);
        styles.put("label", labelStyle);

        return styles;
    }

    /**
     * 创建任务概览工作表
     */
    private void createTaskOverviewSheet(XSSFWorkbook workbook, ScanTask task, List<ScanResult> scanResults,
            Map<String, CellStyle> styles) {
        Sheet sheet = workbook.createSheet("任务概览");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        int rowNum = 0;

        // 任务基本信息
        rowNum = createSectionHeader(sheet, rowNum, "任务基本信息", styles);
        rowNum = createDataRow(sheet, rowNum, "任务ID", task.getId().toString(), styles);
        rowNum = createDataRow(sheet, rowNum, "任务名称", task.getTaskName() != null ? task.getTaskName() : "未命名任务",
                styles);
        rowNum = createDataRow(sheet, rowNum, "任务Status", task.getStatus().getDisplayName(), styles);
        rowNum = createDataRow(sheet, rowNum, "扫描类型", task.getTaskType().getDisplayName(), styles);
        rowNum = createDataRow(sheet, rowNum, "创建时间",
                task.getCreatedAt() != null ? task.getCreatedAt().format(formatter) : "", styles);
        rowNum = createDataRow(sheet, rowNum, "开始时间",
                task.getStartTime() != null ? task.getStartTime().format(formatter) : "", styles);
        rowNum = createDataRow(sheet, rowNum, "结束时间",
                task.getEndTime() != null ? task.getEndTime().format(formatter) : "", styles);
        rowNum = createDataRow(sheet, rowNum, "执行用时", formatDuration(task.getStartTime(), task.getEndTime()), styles);

        rowNum++; // 空行

        // 扫描配置
        rowNum = createSectionHeader(sheet, rowNum, "扫描配置信息", styles);
        if (task.getConfigJson() != null) {
            rowNum = createDataRow(sheet, rowNum, "配置信息", task.getConfigJson(), styles);
        }

        rowNum++; // 空行

        // 统计结果
        rowNum = createSectionHeader(sheet, rowNum, "统计结果", styles);
        rowNum = createDataRow(sheet, rowNum, "问题总数", String.valueOf(scanResults.size()), styles);

        // 按严重程度统计
        Map<String, Long> severityCount = scanResults.stream()
                .collect(Collectors.groupingBy(
                        result -> result.getSeverity() != null ? result.getSeverity().name() : "UNKNOWN",
                        Collectors.counting()));

        rowNum = createDataRow(sheet, rowNum, "高危问题", String.valueOf(severityCount.getOrDefault("HIGH", 0L)), styles);
        rowNum = createDataRow(sheet, rowNum, "中危问题", String.valueOf(severityCount.getOrDefault("MEDIUM", 0L)), styles);
        rowNum = createDataRow(sheet, rowNum, "低危问题", String.valueOf(severityCount.getOrDefault("LOW", 0L)), styles);
        rowNum = createDataRow(sheet, rowNum, "提示问题", String.valueOf(severityCount.getOrDefault("INFO", 0L)), styles);

        // 按分析引擎统计
        long ruleEngineCount = scanResults.stream()
                .filter(result -> "RULE".equals(result.getAnalysisEngine()) || result.getAnalysisEngine() == null)
                .count();
        long aiEngineCount = scanResults.stream()
                .filter(result -> "AI".equals(result.getAnalysisEngine()))
                .count();
        long aiOptimizedCount = scanResults.stream()
                .filter(result -> Boolean.TRUE.equals(result.getAiOptimized()))
                .count();
        long aiConfirmedCount = scanResults.stream()
                .filter(result -> Boolean.TRUE.equals(result.getRuleAnalysisConfirmed()))
                .count();
        long aiRejectedCount = scanResults.stream()
                .filter(result -> Boolean.FALSE.equals(result.getRuleAnalysisConfirmed()))
                .count();

        rowNum = createDataRow(sheet, rowNum, "规则引擎检出", String.valueOf(ruleEngineCount), styles);
        rowNum = createDataRow(sheet, rowNum, "AI引擎检出", String.valueOf(aiEngineCount), styles);
        rowNum = createDataRow(sheet, rowNum, "AI优化问题", String.valueOf(aiOptimizedCount), styles);
        rowNum = createDataRow(sheet, rowNum, "AI确认的问题", String.valueOf(aiConfirmedCount), styles);
        rowNum = createDataRow(sheet, rowNum, "AI否定的问题", String.valueOf(aiRejectedCount), styles);

        // AI分析质量统计
        if (aiEngineCount > 0 || aiOptimizedCount > 0) {
            rowNum++; // 空行
            rowNum = createSectionHeader(sheet, rowNum, "AI分析质量", styles);

            // 计算AI置信度统计
            double avgConfidence = scanResults.stream()
                    .filter(result -> result.getAiConfidenceScore() != null)
                    .mapToDouble(result -> result.getAiConfidenceScore().doubleValue())
                    .average()
                    .orElse(0.0);

            long highConfidenceCount = scanResults.stream()
                    .filter(result -> result.getAiConfidenceScore() != null &&
                            result.getAiConfidenceScore().doubleValue() >= 0.8)
                    .count();

            long lowConfidenceCount = scanResults.stream()
                    .filter(result -> result.getAiConfidenceScore() != null &&
                            result.getAiConfidenceScore().doubleValue() < 0.5)
                    .count();

            rowNum = createDataRow(sheet, rowNum, "AI平均置信度",
                    String.format("%.2f", avgConfidence), styles);
            rowNum = createDataRow(sheet, rowNum, "高置信度问题 (≥0.8)",
                    String.valueOf(highConfidenceCount), styles);
            rowNum = createDataRow(sheet, rowNum, "低置信度问题 (<0.5)",
                    String.valueOf(lowConfidenceCount), styles);
        }

        // 设置列宽
        sheet.setColumnWidth(0, 4000);
        sheet.setColumnWidth(1, 8000);
    }

    /**
     * 创建问题详情工作表
     */
    private void createProblemDetailsSheet(XSSFWorkbook workbook, List<ScanResult> scanResults,
            Map<String, CellStyle> styles) {
        Sheet sheet = workbook.createSheet("问题详情");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = { "序号", "问题名称", "严重程度", "问题类型", "规则ID", "分析引擎",
                "问题描述", "修复建议", "问题SQL片段", "建议SQL",
                "🤖AI优化SQL", "🤖AI置信度", "🤖AI分析说明", "🤖AI验证状态",
                "文件名", "行号" };

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(styles.get("header"));
        }

        // 填充数据
        int rowNum = 1;
        for (int i = 0; i < scanResults.size(); i++) {
            ScanResult result = scanResults.get(i);
            Row row = sheet.createRow(rowNum++);

            createDataCell(row, 0, String.valueOf(i + 1), styles.get("data"));
            createDataCell(row, 1, result.getRuleName() != null ? result.getRuleName() : "", styles.get("data"));
            createDataCell(row, 2, result.getSeverity() != null ? result.getSeverity().name() : "", styles.get("data"));
            createDataCell(row, 3, result.getIssueType() != null ? result.getIssueType().name() : "",
                    styles.get("data"));
            createDataCell(row, 4, result.getRuleId() != null ? result.getRuleId() : "", styles.get("data"));

            // 分析引擎信息
            String engineInfo = getAnalysisEngineInfo(result);
            createDataCell(row, 5, engineInfo, styles.get("data"));

            // 问题描述 - 优先显示AI描述
            String issueDesc = result.getAiIssueDescription() != null && !result.getAiIssueDescription().isEmpty()
                    ? "🤖AI分析: " + result.getAiIssueDescription()
                    : (result.getIssueDescription() != null ? result.getIssueDescription() : "");
            createDataCell(row, 6, issueDesc, styles.get("data"));

            createDataCell(row, 7, result.getSuggestion() != null ? result.getSuggestion() : "", styles.get("data"));
            createDataCell(row, 8, result.getOriginalSql() != null ? result.getOriginalSql() : "", styles.get("data"));
            createDataCell(row, 9, result.getSuggestedSql() != null ? result.getSuggestedSql() : "",
                    styles.get("data"));

            // AI相关字段
            createDataCell(row, 10, result.getOptimizedSql() != null ? result.getOptimizedSql() : "",
                    styles.get("data"));
            createDataCell(row, 11, formatAiConfidence(result.getAiConfidenceScore()), styles.get("data"));
            createDataCell(row, 12,
                    result.getOptimizationExplanation() != null ? result.getOptimizationExplanation() : "",
                    styles.get("data"));
            createDataCell(row, 13, getAiVerificationStatus(result), styles.get("data"));

            createDataCell(row, 14, result.getFilePath() != null ? result.getFilePath() : "", styles.get("data"));
            createDataCell(row, 15, result.getLineNumber() != null ? result.getLineNumber().toString() : "",
                    styles.get("data"));
        }

        // 设置列宽 - 调整为16列
        int[] columnWidths = { 1500, 8000, 2500, 2500, 3000, 2500, 12000, 12000, 12000, 12000,
                12000, 2500, 12000, 3000, 6000, 1500 };
        for (int i = 0; i < columnWidths.length; i++) {
            sheet.setColumnWidth(i, columnWidths[i]);
        }
    }

    /**
     * 获取分析引擎信息
     */
    private String getAnalysisEngineInfo(ScanResult result) {
        String engine = result.getAnalysisEngine();
        boolean isAiOptimized = Boolean.TRUE.equals(result.getAiOptimized());

        if ("AI".equals(engine)) {
            return "🤖AI引擎";
        } else if ("RULE".equals(engine) || engine == null) {
            if (isAiOptimized) {
                return "规则引擎+🤖AI优化";
            } else {
                return "规则引擎";
            }
        } else {
            return engine;
        }
    }

    /**
     * 格式化AI置信度
     */
    private String formatAiConfidence(BigDecimal confidence) {
        if (confidence == null) {
            return "";
        }

        double score = confidence.doubleValue();
        String percentage = String.format("%.1f%%", score * 100);

        if (score >= 0.8) {
            return "🟢高 " + percentage;
        } else if (score >= 0.5) {
            return "🟡中 " + percentage;
        } else {
            return "🔴低 " + percentage;
        }
    }

    /**
     * 获取AI验证状态
     */
    private String getAiVerificationStatus(ScanResult result) {
        Boolean confirmed = result.getRuleAnalysisConfirmed();

        if (confirmed == null) {
            return "未验证";
        } else if (confirmed) {
            return "✅AI确认";
        } else {
            return "❌AI否定";
        }
    }

    /**
     * 创建章节标题行
     */
    private int createSectionHeader(Sheet sheet, int rowNum, String title, Map<String, CellStyle> styles) {
        Row row = sheet.createRow(rowNum);
        Cell cell = row.createCell(0);
        cell.setCellValue(title);
        cell.setCellStyle(styles.get("title"));
        return rowNum + 1;
    }

    /**
     * 创建数据行
     */
    private int createDataRow(Sheet sheet, int rowNum, String label, String value, Map<String, CellStyle> styles) {
        Row row = sheet.createRow(rowNum);

        Cell labelCell = row.createCell(0);
        labelCell.setCellValue(label);
        labelCell.setCellStyle(styles.get("label"));

        Cell valueCell = row.createCell(1);
        // 对任务概览的值也进行截断处理
        String truncatedValue = truncateOverviewContent(value, label);
        valueCell.setCellValue(truncatedValue);
        valueCell.setCellStyle(styles.get("data"));

        return rowNum + 1;
    }

    /**
     * 截断任务概览内容
     */
    private String truncateOverviewContent(String content, String label) {
        if (content == null) {
            return "";
        }

        int maxLength;
        // 根据标签类型决定最大长度
        if ("配置信息".equals(label)) {
            maxLength = 1000; // 配置JSON可能很长
        } else if ("任务名称".equals(label)) {
            maxLength = 100;
        } else {
            maxLength = 500; // 其他字段的默认长度
        }

        return truncateContent(content, maxLength);
    }

    /**
     * 创建数据单元格
     */
    private void createDataCell(Row row, int columnIndex, String value, CellStyle style) {
        Cell cell = row.createCell(columnIndex);
        // 截断过长的内容，避免Excel报错
        String truncatedValue = truncateContent(value, getMaxCellLength(columnIndex));
        cell.setCellValue(truncatedValue);
        cell.setCellStyle(style);
    }

    /**
     * 截断内容，避免Excel单元格内容过长
     */
    private String truncateContent(String content, int maxLength) {
        if (content == null) {
            return "";
        }

        // Excel单元格最大长度限制为32,767个字符
        if (content.length() <= maxLength) {
            return content;
        }

        // 截断并添加省略号
        String truncated = content.substring(0, maxLength - 3) + "...";
        log.debug("内容被截断: 原始长度={}, 截断后长度={}", content.length(), truncated.length());
        return truncated;
    }

    /**
     * 创建AI分析专用工作表
     */
    private void createAiAnalysisSheet(XSSFWorkbook workbook, ScanTask task, List<ScanResult> aiResults,
            Map<String, CellStyle> styles) {
        Sheet sheet = workbook.createSheet("🤖AI分析详情");

        int rowNum = 0;

        // 标题
        rowNum = createSectionHeader(sheet, rowNum, "🤖 AI分析详细报告", styles);
        rowNum++; // 空行

        // AI分析概览
        rowNum = createSectionHeader(sheet, rowNum, "AI分析概览", styles);
        rowNum = createDataRow(sheet, rowNum, "AI分析问题总数", String.valueOf(aiResults.size()), styles);

        long aiEngineCount = aiResults.stream().filter(r -> "AI".equals(r.getAnalysisEngine())).count();
        long aiOptimizedCount = aiResults.stream().filter(r -> Boolean.TRUE.equals(r.getAiOptimized())).count();
        long aiConfirmedCount = aiResults.stream().filter(r -> Boolean.TRUE.equals(r.getRuleAnalysisConfirmed()))
                .count();
        long aiRejectedCount = aiResults.stream().filter(r -> Boolean.FALSE.equals(r.getRuleAnalysisConfirmed()))
                .count();

        rowNum = createDataRow(sheet, rowNum, "AI引擎直接检出", String.valueOf(aiEngineCount), styles);
        rowNum = createDataRow(sheet, rowNum, "AI优化的问题", String.valueOf(aiOptimizedCount), styles);
        rowNum = createDataRow(sheet, rowNum, "AI确认的规则问题", String.valueOf(aiConfirmedCount), styles);
        rowNum = createDataRow(sheet, rowNum, "AI否定的规则问题", String.valueOf(aiRejectedCount), styles);

        // AI置信度分布
        double avgConfidence = aiResults.stream()
                .filter(r -> r.getAiConfidenceScore() != null)
                .mapToDouble(r -> r.getAiConfidenceScore().doubleValue())
                .average()
                .orElse(0.0);

        rowNum = createDataRow(sheet, rowNum, "平均AI置信度", String.format("%.2f", avgConfidence), styles);
        rowNum++; // 空行

        // 创建详细列表表头
        rowNum = createSectionHeader(sheet, rowNum, "AI分析详细列表", styles);

        Row headerRow = sheet.createRow(rowNum++);
        String[] headers = { "序号", "规则ID", "问题名称", "分析引擎", "AI置信度", "验证状态",
                "原始问题描述", "🤖AI问题描述", "原始建议", "🤖AI优化SQL", "🤖AI优化说明",
                "文件名", "行号" };

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(styles.get("header"));
        }

        // 填充AI分析详细数据
        for (int i = 0; i < aiResults.size(); i++) {
            ScanResult result = aiResults.get(i);
            Row row = sheet.createRow(rowNum++);

            createDataCell(row, 0, String.valueOf(i + 1), styles.get("data"));
            createDataCell(row, 1, result.getRuleId() != null ? result.getRuleId() : "", styles.get("data"));
            createDataCell(row, 2, result.getRuleName() != null ? result.getRuleName() : "", styles.get("data"));
            createDataCell(row, 3, getAnalysisEngineInfo(result), styles.get("data"));
            createDataCell(row, 4, formatAiConfidence(result.getAiConfidenceScore()), styles.get("data"));
            createDataCell(row, 5, getAiVerificationStatus(result), styles.get("data"));
            createDataCell(row, 6, result.getIssueDescription() != null ? result.getIssueDescription() : "",
                    styles.get("data"));
            createDataCell(row, 7, result.getAiIssueDescription() != null ? result.getAiIssueDescription() : "",
                    styles.get("data"));
            createDataCell(row, 8, result.getSuggestion() != null ? result.getSuggestion() : "", styles.get("data"));
            createDataCell(row, 9, result.getOptimizedSql() != null ? result.getOptimizedSql() : "",
                    styles.get("data"));
            createDataCell(row, 10,
                    result.getOptimizationExplanation() != null ? result.getOptimizationExplanation() : "",
                    styles.get("data"));
            createDataCell(row, 11, result.getFilePath() != null ? result.getFilePath() : "", styles.get("data"));
            createDataCell(row, 12, result.getLineNumber() != null ? result.getLineNumber().toString() : "",
                    styles.get("data"));
        }

        // 设置AI分析表列宽
        int[] aiColumnWidths = { 1500, 3000, 8000, 3000, 2500, 3000, 10000, 10000, 10000, 12000, 12000, 6000, 1500 };
        for (int i = 0; i < aiColumnWidths.length; i++) {
            sheet.setColumnWidth(i, aiColumnWidths[i]);
        }

        rowNum += 2; // 空行

        // AI验证详情说明
        rowNum = createSectionHeader(sheet, rowNum, "说明", styles);
        rowNum = createDataRow(sheet, rowNum, "🤖图标说明", "带有🤖图标的内容表示来自AI分析", styles);
        rowNum = createDataRow(sheet, rowNum, "置信度说明", "🟢高(≥80%) 🟡中(50%-80%) 🔴低(<50%)", styles);
        rowNum = createDataRow(sheet, rowNum, "验证状态说明", "✅AI确认问题存在 ❌AI认为问题不存在 未验证=未经AI验证", styles);
        rowNum = createDataRow(sheet, rowNum, "分析引擎说明", "AI引擎=纯AI分析；规则引擎+AI优化=规则检出后AI优化", styles);
    }

    /**
     * 根据列类型获取最大内容长度
     */
    private int getMaxCellLength(int columnIndex) {
        switch (columnIndex) {
            case 0: // 序号
                return 10;
            case 1: // 问题名称
                return 200;
            case 2: // 严重程度
                return 20;
            case 3: // 问题类型
                return 50;
            case 4: // 规则ID
                return 50;
            case 5: // 分析引擎
                return 50;
            case 6: // 问题描述
                return 1000;
            case 7: // 修复建议
                return 1000;
            case 8: // 问题SQL片段
                return 2000;
            case 9: // 建议SQL
                return 2000;
            case 10: // 🤖AI优化SQL
                return 2000;
            case 11: // 🤖AI置信度
                return 30;
            case 12: // 🤖AI分析说明
                return 1000;
            case 13: // 🤖AI验证状态
                return 30;
            case 14: // 文件名
                return 300;
            case 15: // 行号
                return 10;
            default:
                return 500; // 默认最大长度
        }
    }

    /**
     * 格式化执行时长
     */
    private String formatDuration(LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime == null || endTime == null)
            return "未知";

        long seconds = java.time.Duration.between(startTime, endTime).getSeconds();
        if (seconds < 60) {
            return seconds + "秒";
        }

        long minutes = seconds / 60;
        long remainingSeconds = seconds % 60;
        return minutes + "分" + remainingSeconds + "秒";
    }
}